package com.hqyj.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.hqyj.excepiton.JwtException;
import com.hqyj.utile.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 项目:exam-springboot-230701
 * 描述: jwt拦截校验
 * 时间:2023/10/7 13:54
 * 作者:admin
 * 版本:1.0
 **/
public class JwtInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("Authorization");
        //1 判断是否为空
        if(StringUtils.isEmpty(token)){
            throw new JwtException(300,"请重新登录","token为空");
        }
        //2 获取token的用户id,判断token是否是伪造的
        String id =JwtUtil.getAudience(token);
        if(id==null){
            throw new JwtException(300,"请重新登录","token错误");
        }
        //3 判断token是否过期
        //获取盐值
        String salt = JwtUtil.getClaimByName(token,"jwtSalt").asString();
        DecodedJWT jwt = JwtUtil.verifyToken(token,salt);
        if(jwt==null){
            throw new JwtException(300,"请重新登录","token过期");
        }

        return true;
    }
}
